﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebForm.SystemTheme
{
    public partial class NavigationPanel : System.Web.UI.UserControl, INavigationPanel
    {
        private IEnumerable<Core.Navigation> _navigations;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void Initiate(IEnumerable<Core.Navigation> navigations, IEnumerable<Core.Shortcut> shortcuts)
        {
            _navigations = navigations;

            if (!IsPostBack)
            {
                foreach (var item in navigations)
                {
                    MenuItem menuItem = new MenuItem(item.Caption, item.Id.ToString());

                    if (item.Children != null)
                    {
                        BuildMenu(menuItem, item);
                    }
                    _ctlMenu.Items.Add(menuItem);
                }
            }
        }

        private void BuildMenu(MenuItem parentItem, Core.Navigation parentNavigation)
        {
            foreach (var item in parentNavigation.Children)
            {
                MenuItem menuItem = new MenuItem(item.Caption, item.Id.ToString());
                parentItem.ChildItems.Add(menuItem);
            }
        }

        public event NavigatingEventHandler Navigating;

        protected void _ctlMenu_MenuItemClick(object sender, MenuEventArgs e)
        {
            Guid navigationId = new Guid(e.Item.Value);
            Core.Navigation navigation = GetNavigation(navigationId);

            if (Navigating != null)
            {
                Navigating(this, new NavigatingEventArgs(e.Item.Text, navigation));
            }
        }

        private Core.Navigation GetNavigation(Guid navigationId)
        {
            foreach (var item in _navigations)
            {
                if (item.Id == navigationId)
                {
                    return item;
                }

                Core.Navigation match = GetNavigation(item, navigationId);
                if (match != null)
                {
                    return match;
                }
            }
            return null;
        }
        
        private Core.Navigation GetNavigation(Core.Navigation navigation, Guid navigationId)
        {
            if (navigation.Children == null)
            {
                return null;
            }

            foreach (var item in navigation.Children)
            {
                if (item.Id == navigationId)
                {
                    return item;
                }

                Core.Navigation match = GetNavigation(item, navigationId);
                if (match != null)
                {
                    return match;
                }
            }
            return null;
        }
    }
}